﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Com.StellmanGreene.CSVReader;
using System.Data;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;

namespace nGSO.Utils
{
    /// <summary>
    /// Access for optima for nGSO result validation
    /// </summary>
    public class OptimumCsvProvider
    {
        public void FillFromFile(Dictionary<double[], List<double[]>> container, string fileName)
        {
            string content = File.ReadAllText(fileName, Encoding.UTF8);

            FillFromString(container, content);
        }

        private static void FillLocs(IDictionary<double[], List<double[]>> container, DataTable dt)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow row = dt.Rows[i];

                int dims = row.ItemArray.Length;
                double[] loc = new double[dims];

                for (int j = 0; j < dims; j++)
                {
                    string s =  row.ItemArray[j].ToString();
                    loc[j] = Convert.ToDouble(s, CultureInfo.InvariantCulture);
                }

                container.Add(loc, new List<double[]>());
            }
        }

        public void FillFromString(IDictionary<double[], List<double[]>> container, string encodedCsv)
        {
            CSVReader reader = new CSVReader(encodedCsv.Replace("|", "\r\n"));
            DataTable dt = reader.CreateDataTable(false);

            FillLocs(container, dt);
        }

        public List<double[]> CreateFromConfigValue(string encodedOptima)
        {
            Match fileName = Regex.Match(encodedOptima, "@file=(.+)@");
            List<double[]> optimums = new List<double[]>();
            
            CSVReader reader = null;

            if (fileName.Success)
                reader = new CSVReader(new FileInfo(fileName.Groups[1].Value));
            else
                reader = new CSVReader(encodedOptima.Replace("|", "\r\n"));

            DataTable dt = reader.CreateDataTable(false);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow row = dt.Rows[i];

                int dims = row.ItemArray.Length;
                double[] loc = new double[dims];

                for (int j = 0; j < dims; j++)
                {
                    string s = row.ItemArray[j].ToString();
                    loc[j] = Convert.ToDouble(s, CultureInfo.InvariantCulture);
                }

                optimums.Add(loc);
            }

            return optimums;
        }
    }
}
